var amapFile = require('../../libs/amap-wx.js');
var config = require('../../libs/config.js');
const exhibitionTotalData = require('../../data/exhibition_total_data');
var markersData = [];
var currentId =-1; //当前选中的那个marker点
const exhibitionTotals = exhibitionTotalData.exhibitionTotalData;

//进行选择：用于底部信息弹窗：根据点击的是哪个i(exhibitionid)查询“总数据A”获取到相关信息（图片，名字，地址，时间，备注）
const onmarkerIdByUser =[1,2,3]
Page({
  data: {
    markers: [],
    poisData: [],
    latitude: '',
    longitude: '',
    textData: {},
    city: '',
    scale: 5,
    //弹窗数据
    exhibitionImage: '',
    exhibitionName: '',
    exhibitionProfile: '',
    exhibitionAddress: '',
    exhibitionNote: '',
    exhibitionTime: '',
    //样式
    bottomDistance: '102px',
    maskDisplay: 'none',
    detailInfoDisplay: 'none',
    //是否为搜索
    isSearch: false,
  },
  
  // 点击标记后触发事件
  makertap: function(e) {
    var id = e.markerId;
    var that = this;
    //that.doMarkerByI(markersData,id);
    that.changeMarkerColor(markersData,id);
    //that.getUserLocation();
  },

  //页面初始加载时
  onLoad: function(e) {
     //接口获取到全部的展馆数据“A”
    //console.log(exhibitionTotalData.exhibitionTotalData);
    var that = this;
    // 获取精简数组对象,用于initMap：只需要字段：展馆id，展馆名字，展馆经纬度“B”
    const simplifiedExhibitions = exhibitionTotals.filter(item => !isNaN(item.exhibitionLatitude) && !isNaN(item.exhibitionLongitude)).map((item,index) => {
      return {
        id: item.id,
        exhibitionName: item.exhibitionName,
        latitude: item.exhibitionLatitude,
        longitude: item.exhibitionLongitude
      };
    });//B <= A

    markersData = simplifiedExhibitions;
    markersData.forEach(marker=> {
      if(onmarkerIdByUser.includes(marker.id)){
        //表示当前用户的这个标记点已经打过卡了
        marker.iconPath = '../../img/marker_checked.png';
      }else{
        marker.iconPath = '../../img/marker.png';
      }
      marker.height = 22;
      marker.width = 22;
      marker.callout = {
          content: '📷' + marker.exhibitionName, // 显示POI名称和展馆图片 B
          color: '#000000', 
          fontSize: 14, 
          borderRadius: 10, 
          bgColor: '#ffffff', 
          padding: 10, 
          display: 'ALWAYS', // 气泡始终显示 todo1.获取地图缩放的scale 2.当scale>=16时再显示
          textAlign: 'center'
        };
    });
    that.setData({
      scale: 20,
      markers: markersData
    })
    //配置中心点(如果没有定位权限会提醒)
    that.getUserLocation();
    //表示从搜索页面回来的
    if(e&&e.keywords){
      that.searchMarkerShowPoiList(e);
    }
  },

  //搜索框
  bindInput: function(e){
    var that = this;
    var url = '../inputtips/input';
    if(e.target.dataset.latitude && e.target.dataset.longitude && e.target.dataset.city){
      var dataset = e.target.dataset;
      url = url + '?lonlat=' + dataset.longitude + ',' + dataset.latitude + '&city=' + dataset.city;
    }
    wx.redirectTo({
      url: url
    })
  },


  // 将id=i的marker样式改为选中状态 or 未选中状态
  changeSelectMarker(i,isSelectStatus){
    //将item.id === i 的一项的marker更改样式
    markersData.forEach(marker=> {
      if(marker.id == i && isSelectStatus){
        console.log("jinlail")
        //表示更改i为选中
        marker.callout = {
          content: '📷' + marker.exhibitionName, // 显示POI名称和展馆图片 B
          color: '#000000', 
          fontSize: 20, 
          borderRadius: 10, 
          borderWidth: 2,
          bgColor: '#ffffff', 
          padding: 10, 
          display: 'ALWAYS', // 气泡始终显示 todo1.获取地图缩放的scale 2.当scale>=16时再显示
          textAlign: 'center'
        };
      }else{
        marker.callout = {
          content: '📷' + marker.exhibitionName, // 显示POI名称和展馆图片 B
          color: '#000000', 
          fontSize: 14, 
          borderRadius: 10, 
          borderWidth: -1,
          bgColor: '#ffffff', 
          padding: 10, 
          display: 'ALWAYS', // 气泡始终显示 todo1.获取地图缩放的scale 2.当scale>=16时再显示
          textAlign: 'center'
        };
      }
    });
  },

  //为第i个标记点进行标记
  doMarkerByI: function(data,i){
    var that = this;
    that.setData({
      // 用处：最后提交时提交用户新标记了哪些
      textData: {
        name: data[i].name,
        desc: data[i].address
      }
    });
  },

  //点击标记点后的事件：弹出弹框
  changeMarkerColor: function(data,i){
    var that = this;
    currentId = i;
    //i是exhibitionid
    const exhibitionItem = exhibitionTotals.filter(item => item.id == i)[0];
    that.changeSelectMarker(i,true);
    that.setData({
      markers: markersData,
      exhibitionImage: exhibitionItem.exhibitionImage,
      exhibitionName: exhibitionItem.exhibitionName,
      exhibitionProfile: exhibitionItem.exhibitionProfile.substring(0, 12),
      exhibitionAddress: exhibitionItem.exhibitionAddress,
      exhibitionNote: exhibitionItem.exhibitionNote,
      exhibitionTime: exhibitionItem.exhibitionStartTime + ' - ' + exhibitionItem.exhibitionFinishTime,
      bottomDistance: '150px',
      maskDisplay: 'block',
      detailInfoDisplay: 'flex'
    })
  },

  //隐藏弹窗和蒙层 + marker为未选中状态
  hideMaskAndDetailInfo: function(){
    var that = this;
    that.changeSelectMarker(currentId,false);
    that.setData({
      bottomDistance: '102px',
      maskDisplay: 'none',
      detailInfoDisplay: 'none',
      markers: markersData, //！！！！注意更新绑定到视图中的map的marker，样式才能改变！！！
      isSearch: false
    })
  },


  //获取当前用户的当前定位
  getUserLocation: function(){
    var that = this;
    wx.getLocation({
      type: 'gcj02',
      success: function(res) {
        that.setData({
          latitude: res.latitude,
          longitude: res.longitude
        });
      },
      fail: function(){
        wx.showToast({
          title: '请打开定位',
          icon: 'error'
        })
      }
    })
  },


  //搜索标记点后的事件：弹出周边展馆列表 + 选中状态
  searchMarkerShowPoiList(e){
    console.log("e:",e);
    var that = this;
    //todo 根据传递过来的keywords 查询总数组的name===keywords得到唯一一个对象，传入i执行changeMarkerColor()效果类似，只不过底下是列表
    let id = -1;
    const exhibitionSecrchItem = exhibitionTotals.filter(item=>{
      if(item.exhibitionName === e.keywords){
        id = item.id;
        return item;
      }
    })
    currentId = id; //用于点击蒙层时，知道更改哪个marker的样式
    console.log(exhibitionSecrchItem);
    if(exhibitionSecrchItem!={}){
      
      //执行获取周边信息
      let params = {
        success: function(data){
          console.log(data.poisData);
          // 更新中心点，选中状态，显示列表
          that.changeSelectMarker(id,true);
          that.setData({
            poisData: data.poisData,
            markers: markersData,
            latitude: exhibitionSecrchItem[0].exhibitionLatitude,
            longitude: exhibitionSecrchItem[0].exhibitionLongitude,
            isSearch: true,
            bottomDistance: '50vh',
            maskDisplay: 'block',
            detailInfoDisplay: 'flex'
          })
        },
        fail: function(info){
          console.log("搜索失败报错信息：",info)
        }
      }
      params.querykeywords = e.keywords;
      var key = config.Config.key;
      var myAmapFun = new amapFile.AMapWX({key: key});
      myAmapFun.getPoiAround(params);
    }
  }

})